package com.itheima.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.R;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.util.SMSUtils;
import com.itheima.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * reggie-com.itheima.Controller
 * Administrator
 * 2023-03-12
 * 19:06
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

@Autowired
private UserService userService;

@Autowired
RedisTemplate redisTemplate;


    @PostMapping("/sendMsg")
    public R getsendMsg(@RequestBody User user, HttpSession session){
        String phone = user.getPhone();
        //生成验证码
        Integer integer = ValidateCodeUtils.generateValidateCode(4);
        log.info("验证码{}",integer);


        ////发送验证码
        //SMSUtils.sendMessage("阿里云短信测试","SMS_154950909","19855804793",integer.toString());

        //将该验证码存入到session中，使用手机号作为key，值就是验证码
        //session.setAttribute(phone,integer.toString());

        //redis优化:
        redisTemplate.opsForValue().set(phone,integer.toString(),2, TimeUnit.MINUTES);

        return R.success("验证码发送成功");
    }

    @PostMapping("/login")
    public R checkSendMsgLogin(@RequestBody Map map, HttpSession session){
        String phone = (String) map.get("phone");
        String code = (String) map.get("code");
        //真实验证码
        //Object sendMsg = session.getAttribute(phone);

        //redis 获取
        Object sendMsg = redisTemplate.opsForValue().get(phone);

        if (sendMsg!=null&&sendMsg.equals(code)){
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            lqw.eq(User::getPhone,phone);
            User user = userService.getOne(lqw);
            if (user==null){;
                User user1 = new User();
                user1.setStatus(1);
                user1.setPhone(phone);
                userService.save(user1);
                session.setAttribute("user",user1.getId());
                //删除redis
                redisTemplate.delete(phone);
                return R.success("登录成功");
            }else {
                session.setAttribute("user",user.getId());

                //登录成功删除redis
                redisTemplate.delete(phone);
                return R.success("登录成功");
            }
        }
        return  R.error("登录失败");
    }

    @PostMapping("/loginout")
    public  R loginout(HttpSession session){
        Object user = session.getAttribute("user");
        session.invalidate();
        return R.success("退出成功");
    }


}
